package finder;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.project.institute.DAO.InstituteListFragmentDAO;
import com.project.trac.R;

import core.modules.DatabaseConnector;

public class SubjectViewer extends InstituteListFragmentDAO {

	private final int CONTEXT_MENU_DROP = 1;
	
	public static ListFragment newInstance(Context context) {
		SubjectViewer lf = new SubjectViewer();
		return lf;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.generic_list, null);
		
		new AsynchronousTask().execute("initialize");
		return root;
	}
	
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		OnItemClickListener joinGroup = new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> av, View view, int position, long id) {
				
				ArrayList<String> list = new ArrayList<String>();
				
				StringTokenizer tokenizer = new StringTokenizer(av.getItemAtPosition(position).toString(),",=");
				while (tokenizer.hasMoreTokens() ) {  
					list.add(tokenizer.nextToken());  
				}  
				
				setScheduleID(Integer.valueOf(list.get(list.indexOf(" k7")+1)));
				setSubjectName(list.get(list.indexOf(" k1")+1));
				
				registerForContextMenu(getListView());
				getActivity().openContextMenu(getListView());
				
			}
			
			
		};


		getListView().setOnItemClickListener(joinGroup);

	}
	
	public void onAttachedToWindow() {
		super.getActivity().onAttachedToWindow();
		Window window = getActivity().getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}	
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("Select Action");
		menu.add(Menu.NONE, CONTEXT_MENU_DROP, Menu.NONE, "Drop " + getSubjectName());
	}
	
	
	@SuppressWarnings("deprecation")
	@Override
	public boolean onContextItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case CONTEXT_MENU_DROP:
			
			AlertDialog ad = new AlertDialog.Builder(getActivity()).create();
			ad.setCancelable(false); // This blocks the 'BACK' button
			ad.setMessage("Really drop " + getSubjectName() + "?");
			ad.setButton("Yes", new DialogInterface.OnClickListener() {
			    @Override
			    public void onClick(DialogInterface dialog, int which) {
			    	new AsynchronousTask().execute("drop");
			        dialog.dismiss();
			        
					getActivity().getSupportFragmentManager().popBackStack();
					getActivity().startActivity(getActivity().getIntent());
			    }
			});
			
			ad.setButton2("No", new DialogInterface.OnClickListener() {
			    @Override
			    public void onClick(DialogInterface dialog, int which) {
			        dialog.dismiss();
			    }
			});
			ad.show();
			
			break;
		}
		return super.onContextItemSelected(item);
	}
	
	private class AsynchronousTask extends AsyncTask<String, String, String> {

		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();

		ListAdapter listAdapter;
		
		String KEY_CAT = "k1";
		String KEY_SECTION = "k2";
		String KEY_DAYS = "k3";
		String KEY_TIME = "k4";
		String KEY_ROOM = "k5";
		String KEY_INSTRUCTOR = "k6";
		String KEY_SCHEDULE_ID = "k7";
		
		String CATALOG_NUMBER = "v1";
		String VALUE_INSTRUCTOR = "v2";
		
		int rowCount;

		
		protected void onPreExecute() {
			super.onPreExecute();
		}

		protected String doInBackground(String... args) {
			
			try {
				if (args[0].equalsIgnoreCase("initialize")) {
					ResultSet rs = DatabaseConnector.getStatement().executeQuery(
							"SELECT curriculum.catalognumber, schedule.section, schedule.days, schedule.time, "
									+ " schedule.room, users.title, users.firstname, users.lastname, sid"
									+ " FROM gradesheet"
									+ " INNER JOIN schedule ON schedule.cid = gradesheet.cid "
									+ " INNER JOIN users ON users.id = schedule.uid"
									+ " INNER JOIN curriculum ON curriculum.id = gradesheet.cid"
									+ " WHERE gradesheet.uid = " + getUserID());

						while (rs.next()) {
							m = new HashMap<String, String>();
							
							CATALOG_NUMBER = rs.getString("catalognumber");
							VALUE_INSTRUCTOR = rs.getString("title") + " " + rs.getString("firstname")  
										   + " " + rs.getString("lastname");
							
							m.put(KEY_CAT, CATALOG_NUMBER);
							m.put(KEY_SECTION, rs.getString("section"));
							m.put(KEY_DAYS, rs.getString("days"));
							m.put(KEY_TIME, rs.getString("time"));
							m.put(KEY_ROOM, rs.getString("room"));
							m.put(KEY_INSTRUCTOR, VALUE_INSTRUCTOR);
							m.put(KEY_SCHEDULE_ID, rs.getString("sid"));
							arrayList.add(m);
						}
						
						rowCount = arrayList.size();
				}
				
				if (args[0].equalsIgnoreCase("drop")) {
					DatabaseConnector.getConnection().setAutoCommit(false);
					PreparedStatement pps = DatabaseConnector.getConnection().prepareStatement("DELETE FROM gradesheet WHERE sid = ? AND uid = ?");
					
					pps.setInt(1, getScheduleID());
					pps.setInt(2, getUserID());

					pps.executeUpdate();
					pps.clearParameters();
					pps.close();
				}
				
			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			}

			return null;
		}


		protected void onPostExecute(String postExecute) {
			
			TextView msg = new TextView(getActivity());
			
			if (rowCount == 0) {
				msg.setText("No enrolled subjects found.");
			} else if (rowCount == 1) {
				msg.setText("You are already enrolled\nin " + rowCount + " Subject!");
			} else if (rowCount > 1) {
				msg.setText("You are already enrolled\nin " + rowCount + " Subjects!");
			}
			msg.setTextAppearance(getActivity(), R.style.alert_message);
			msg.setGravity(Gravity.CENTER);
			Toast.makeText(getActivity().getApplicationContext(), msg.getText().toString(), Toast.LENGTH_SHORT).show();
			
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					listAdapter = new SimpleAdapter(getActivity(), arrayList,
							R.layout.student_course_enrolled_detail, 
							new String[] { KEY_CAT, KEY_SECTION,  KEY_DAYS,  KEY_TIME,  KEY_ROOM,  KEY_INSTRUCTOR, KEY_SCHEDULE_ID }, 
							new int[] { R.id.r_key_cat_new, R.id.actualSection,  R.id.actualDay,  R.id.actualTime,  R.id.actualRoom,  R.id.actualInstructor, 0});

					setListAdapter(listAdapter);
				}
			});
		}
	} 
	
}